package ru.papergames.model.binsocket.data
{
	import flash.utils.ByteArray;
	import flash.utils.Endian;

	public class ExtByteArray extends ByteArray
	{
		
		public var recieved:Boolean = false;
		
		public function ExtByteArray()
		{
			super();
			this.endian = Endian.LITTLE_ENDIAN;
		}
		
		public function cleanup():void {
			this.clear();
			//this.length = 0;
		}
		
		public function readLong():Number {
			var val:Number = this.readUnsignedInt();
			val += this.readUnsignedInt()*4294967296;
			return val;
		}
		
		public function writeLong(n:Number):void {
			n = Math.round(n);
			
			var hi:int = Math.floor(n/4294967296);
			var lo:int = n - hi*4294967296;
			
			this.writeUnsignedInt(lo);
			this.writeUnsignedInt(hi);
		}
		
		override public function readBoolean():Boolean {
			return readUnsignedByte() == 1;
		}
		
		public function writeUTFString(s:String):void {			
			this.writeUTFBytes(s);
			this.writeByte(0);
		}
		
		/**
		 * Check size and fix first two bytes
		 * 
		 * */
		public function validateSize():void {
			if (this.length < 3) {
				this.cleanup();
				return;
			}
			
			var size:int = this.length;
			
			this[1] = size >>> 8;
			this[0] = this.length - 256*this[1];
			
		}
		
		override public function toString():String {
			var bytesStr:String = '';
			var oldPos:uint = position;
			
			position = 0;
			
			while (this.position < this.length) {
				var byteStr:String = this.readUnsignedByte().toString(16).toLocaleUpperCase();
				bytesStr += (byteStr.length < 2 ? '0' : '') + byteStr + ' ';
			}
			
			position = oldPos;
			
			return bytesStr;
		}
		
	}
}